package api

import (
	"fmt"
	"github.com/fvbock/endless"
	"github.com/spf13/cobra"
	"tdy-backend/bootstrap"
	"tdy-backend/global"
	"tdy-backend/pkg/socket"
)

var (
	configYml string
	StartCmd  = &cobra.Command{
		Use:          "server",
		Short:        "Start API server",
		Example:      "go server -c config/settings.yml",
		SilenceUsage: true,
		PreRun: func(cmd *cobra.Command, args []string) {
			setup()
		},
		RunE: func(cmd *cobra.Command, args []string) error {
			return run()
		},
	}
)

func setup() {
	usageStr := `.----------------.  .----------------.  .----------------.` + "\n" + `| .--------------. || .--------------. || .--------------. |` + "\n" + `| |  _________   | || |  ________    | || |  ____  ____  | |` + "\n" + `| | |  _   _  |  | || | |_   ___ .  | || | |_  _||_  _| | |` + "\n" + `| | |_/ | | \_|  | || |   | |   . \ | || |   \ \  / /   | |` + "\n" + `| |     | |      | || |   | |    | | | || |    \ \/ /    | |` + "\n" + `| |    _| |_     | || |  _| |___.' / | || |    _|  |_    | |` + "\n" + `| |   |_____|    | || | |________.'  | || |   |______|   | |` + "\n" + `| |              | || |              | || |              | |` + "\n" + ` | '--------------' || '--------------' || '--------------' |` + "\n" + ` '----------------'  '----------------'  '----------------'`
	fmt.Printf("%s\n", usageStr)
	global.TYD_CONFIG = bootstrap.Viper(configYml)
	global.TYD_LOGGER = bootstrap.Zap()
	global.TYD_DB = bootstrap.Gorm()
	global.TYD_SOCKET = bootstrap.Socket()
	hub := socket.NewHub()
	global.TYD_HUB = hub
	go hub.Run()
	// global.TYD_CACHE = bootstrap.BigCache(10*time)
}
func init() {
	StartCmd.PersistentFlags().StringVarP(&configYml, "config", "c", "config/app.yaml", "Start server with provided configuration file")
	// AppRouters = append(AppRouters, router.InitRouter)
	// boot.InitStatic()

}
func run() error {
	endless.ListenAndServe(fmt.Sprintf("%s:%d", global.TYD_CONFIG.Get("app.host"), global.TYD_CONFIG.Get("app.port")), bootstrap.InitRouter())
	//srv := &http.Server{
	//	Addr:    fmt.Sprintf("%s:%d", global.TYD_CONFIG.Get("app.host"), global.TYD_CONFIG.Get("app.port")),
	//	Handler: bootstrap.InitRouter(),
	//}
	//go func() {
	//	if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
	//		log.Fatal("listen: ", err)
	//	}
	//}()
	//// 等待中断信号以优雅地关闭服务器（设置 5 秒的超时时间）
	//quit := make(chan os.Signal)
	//signal.Notify(quit, os.Interrupt)
	//<-quit
	//log.Println("正在关闭服务 ...")
	//ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	//defer cancel()
	//if err := srv.Shutdown(ctx); err != nil {
	//	log.Fatal("服务关闭失败:", err)
	//}
	//log.Println("服务退出")
	return nil
}
